package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.search.dtos.UserSearchDto;
import com.heima.search.service.IAssociateService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class AssociateServiceImpl implements IAssociateService {

    @Autowired
    private RestHighLevelClient client;

    /**
     * 自动补全功能
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {
        //2.创建搜索请求对象，并指定索引名称
        SearchRequest searchRequest=new SearchRequest("app_info_article");
        //3,执行DSL
        searchRequest.source().suggest(
                new SuggestBuilder().addSuggestion(
                        "articleSuggestion",//指定自动补全名称
                        SuggestBuilders.completionSuggestion("suggestion")//执行的字段名称
                        .prefix(dto.getSearchWords())//自动补全的是哪个字段
                        .skipDuplicates(true)//跳过重复的
                        .size(10)//只自动补全10条数据
                )
        );

        //1.查询
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        //4.数据封装
        List<String> resultList=new ArrayList<>();
        Suggest suggest = searchResponse.getSuggest();
       CompletionSuggestion articleSuggestion = suggest.getSuggestion("articleSuggestion");
        List<CompletionSuggestion.Entry.Option> options = articleSuggestion.getOptions();
        for (CompletionSuggestion.Entry.Option option : options) {
            resultList.add(option.getText().toString());
        }

        return ResponseResult.okResult(resultList);
    }
}
